<?php
/**
 * User: @lose
 * Date: 2020/7/28
 * Time: 2:02 下午
 */

namespace Beerus\Modules\Store\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use Biz\model\store\StoreOrder as mOrder;
use Biz\model\store\StoreAccount as mAccount;
use Biz\service\admin\StoreAccount as sAccount;
use Biz\service\admin\StoreOrder as sOrder;
use Illuminate\Support\MessageBag;
use Doraemon\tools\ImgUrl;
use Doraemon\cache\User as cUser;
use Doraemon\cache\UserAuthStatus as cUserAuthStatus;
use Doraemon\model\Member as mMember;
use Biz\pockets\excel\DownExcel;



class OrderController extends Controller
{
    public function index(Content $content, Request $request)
    {
        $url = $_SERVER["REQUEST_URI"];
        $data_url = explode('?',$url);
        $export_url = $data_url[1] ? :'';

        $page = $request->input('page', 1);
        $perPage = $request->input('per_page',20);
        $condition = self::GeTCondition($request);
        $limit = [
            ($page - 1) * $perPage, $perPage
        ];
        $result = sOrder::getListByWhere($condition , $limit);
        $grid = new pGridDataModel($result['list'], $result['total'], [
            'per_page' => $perPage
        ]);

        $gridList = Admin::grid($grid,
            function (Grid $grid) use ($export_url) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->filter(function ($filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('store_id', '店铺id');
                        $filter->equal('server_type', '服务商类型')->select(mAccount::SERVER_TYPE_MAP);
                        $filter->equal('payment_method', '支付方式')->select(mOrder::TRANSFER_METHOD);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('store_name', '门店名称')->placeholder('门店名称');
                        $filter->dropDown('pay_time', [
                            'pay_time' => '支付时间'
                        ])->betweenDatetime();
                    });
                    $filter->expand();//默认展开
                });

                $grid->tools(function ($tools) use ($export_url) {
                    $url = url('/admin/store/order/exportData?'.$export_url);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="导出" target="_blank" href="'.$url.'"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a>
</div>';
                    $tools->append($button);
                });
                $grid->column("id", '订单号');
                $grid->column("store_id", '门店id');
                $grid->column("store_name", '门店名称');
                $grid->column('server_type', '服务商类型');
                $grid->column("pay_time", '支付时间');
                $grid->column("auth_start_time", '服务时间')->display(function ($title, Grid\Column $column) {
                    $html = '<span style="color:royalblue">开始:</span>'.date("Y-m-d" ,strtotime($this->auth_start_time)) .'<br/><span style="color:royalblue" >结束:</span>'.date("Y-m-d" ,strtotime($this->auth_end_time)) ;
                    return $html;
                });;
                $grid->column("transact_serial_num", '流水号');
                $grid->column('payment_method', '支付方式');
                $grid->column("admin_id", '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                })->width(70);
                $grid->disableActions();
            });
        $content->row($gridList);
        return $content
            ->header('门店订单管理')
            ->description(' ')
            ->breadcrumb(['text' => 'user']);
    }


    public function GeTCondition($request){

        $condition = [];
        if( $request->input('store_id')){
            $condition['store_id'] = $request->input('store_id');
        }

        if($request->input('store_name')){
            $condition['store_name'] = $request->input('store_name');
        }

        if($request->input('payment_method')){
            $condition['payment_method'] = $request->input('payment_method');
        }

        if( $request->input('server_type')){
            $condition['server_type'] = $request->input('server_type');
        }

        if($request->input('pay_time')['start'] && $request->input('pay_time')['end']){
            $condition['start_time'] = $request->input('pay_time')['start'];
            $condition['end_time'] = $request->input('pay_time')['end'];
        }

        return $condition;
    }

    public function createOrder(Content $content, Request $request,$a_id=0){
        $order_info = sOrder::getOrderByAid($a_id);

        $order_info['account_id'] = $a_id;
        $form = new Form($order_info);
        $form->hidden('account_id');
        if($order_info){
            $form->hidden('id');
        }
        $form->text('store_id', '门店id')->readonly();
        $form->text('uid', '账户uid')->readonly();
        $form->text('store_name', '门店名称')->width("300px")->readonly();
        $form->datetime('auth_start_time', '认证开始时间')->width("300px")->readonly()->required();
        $form->datetime('auth_end_time', '认证到期时间')->width("300px")->required();
        $form->text('transact_serial_num','交易流水号')->width('300px')->required();
        $form->imgUpload('transact_proof_pic', '交易流凭证', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
        $form->text('payment_amount', '支付金额')->width("200px")->required();
        $form->select("payment_method",'支付方式')->options(mOrder::TRANSFER_METHOD)->required();
        $form->disableReset();
        $form->action('/admin/store/order/save');

        return $content
            ->header('账单信息')
            ->row($form);
    }


    public function saveOrder(Request $request)
    {
        $params = $request->all();
        try {
            $account_id = $params['account_id'];
            $uid = $params['uid'];
            $store_id = $params['store_id'];
            $auth_start_time = $params['auth_start_time'];
            $auth_end_time = $params['auth_end_time'];
            $transact_serial_num = $params['transact_serial_num'];
            $transact_proof_pic = $params['transact_proof_pic'];
            $payment_amount = $params['payment_amount'];
            $payment_method = $params['payment_method'];
            if(empty($transact_proof_pic)){
                $error = new MessageBag([
                    'title' => '流水凭证缺失'
                ]);
                return back()->with(compact('error'));
            }
            $data  =[
                'account_id' => $account_id ,
                'store_id' => $store_id,
                'store_uid' => $uid,
                'transact_serial_num' => $transact_serial_num,
                'transact_proof_pic' => $transact_proof_pic,
                'payment_amount' => $payment_amount,
                'payment_method' => $payment_method,
                'admin_id' => Admin::user()->id,
                'pay_status' => mOrder::HAVE_PAID,
                'pay_time' => date("Y-m-d H:i:s" , time()),
                'auth_start_time' => $auth_start_time ,
                'auth_end_time' => $auth_end_time

            ];
            $order_no = sOrder::createOrderNo($account_id , $uid);
            if(empty($order_no)){
                $error = new MessageBag([
                    'title' => '订单号生成失败'
                ]);
                return back()->with(compact('error'));
            }
            $data['order_no'] = $order_no;
            $data['addtime'] = date("y-m-d H:i:s" , time());
            sOrder::InsertOrder($data);
            sAccount::updateAccount($account_id , ['auth_start_time' => $auth_start_time , 'auth_end_time' => $auth_end_time ,'auth_status' => mAccount::AUTH_SUCC]);
            //改变用户的身份
            if($uid){
                //更新主账户类别，普通用户改变类别，品牌用户不用改变类别
                mMember::updateUserInfo($uid, ['type' => mMember::AUTH_USER_STORE]);
                cUser::deleteUserInfo($uid);
                // 标记用户强制退出
                cUserAuthStatus::setAuthType($uid, mMember::AUTH_USER_STORE);
            }
            //更新basic 状态
            sAccount::updateStoreBasic($store_id ,['store_status' =>1]);
            //改变用户的身份
            $success = new MessageBag([
                'title' => '添加成功'
            ]);
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '请重试,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        return redirect('/admin/store/basic/index')->with(compact('success'));
    }


    /*导出数据
    *
    * */
    public function exportData(Request $request)
    {
        $request = $request->all();
        $condition= [];
        if( $request['store_id']){
            $condition['store_id'] = $request['store_id'];
        }

        if($request['store_name']){
            $condition['store_name'] = $request['store_name'];
        }

        if($request['payment_method']){
            $condition['payment_method'] = $request['payment_method'];
        }

        if( $request['server_type']){
            $condition['server_type'] = $request['server_type'];
        }

        if($request['pay_time']['start'] && $request['pay_time']['end']){
            $condition['start_time'] = $request['pay_time']['start'];
            $condition['end_time'] = $request['pay_time']['end'];
        }

        $limit = [
          0,2000
        ];
        $result = sOrder::getListByWhere($condition , $limit);

        $list = [];
        if($result['list'] && is_array($result['list'])){
            foreach ($result['list'] as $val){
               $list[] = [
                   'id' => $val['id'],
                   'store_id' => $val['store_id'],
                   'store_name' => $val['store_name'],
                   'server_type' => $val['server_type'],
                   'payment_amount' => $val['payment_amount'],
                   'pay_time' => $val['pay_time'],
                   'auth_start_time' => $val['auth_start_time'],
                   'auth_end_time' => $val['auth_end_time'],
                   'transact_serial_num' => $val['transact_serial_num'],
                   'payment_method' => $val['payment_method']
               ];
            }
        }
        if (!empty($list)){
            $subject['list'] = $list;
            $subject['total'] = count($result['list']);
        }else{
            $subject['list'] = [];
            $subject['total'] =0;
        }
        $reason = '订单信息';
        $header = ['订单号','门店id', '门店名称','服务商类型','支付金额','支付时间','服务开始时间','服务结束时间','流水号','支付方式'];
        $letter = range('A', 'M');
        $excelObj = new DownExcel();
        $excelObj->setFileName($reason);
        $excelObj->setSheetTitle($reason);

        //设置列宽
        $widths = ['C' => 30, 'D' => 30,'E' => 30, 'F' => 30,'G' => 30, 'H' => 30,'I' => 30];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        foreach ($header as $key => $value) {
            //设置字体
            $excelObj->setFrontName($letter[$key]);
            //设置加粗
            $excelObj->setFrontBold("$letter[$key]1");
            //设置大小
            $excelObj->setFrontSize($letter[$key]);
        }
        $excelObj->create($subject['list'], $header);
    }

}